package edu.iscas.appcheckclient.model.actions;

import android.os.Bundle;
import android.util.Log;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import edu.iscas.appcheckclient.model.Selector;

/**
 * Created by dell on 2016/1/8.
 */
public class MockedHttpResponse extends ParamAction {

    public MockedHttpResponse(Bundle bundle){
        this.name = "mockedhttpresponse";
        buildJSON(bundle);
    }

    private void buildJSON(Bundle bundle){
        this.addParam("protocol", bundle.getString("PROTOCOL"));
        this.addParam("host", bundle.getString("HOST"));
        this.addParam("port", bundle.getString("PORT"));
        this.addParam("file", bundle.getString("FILE"));
        this.addParam("ref", bundle.getString("REF"));
        this.addParam("userinfo", bundle.getString("USERINFO"));

        byte[] response = bundle.getByteArray("RESPONSE");
        ByteArrayInputStream bais = new ByteArrayInputStream(response != null ? response : new byte[0]);
        BufferedReader br = new BufferedReader(new InputStreamReader(bais));
        String line;
        StringBuilder sb = new StringBuilder();
        try {
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            this.addParam("response", sb.toString());
        } catch (IOException e) {
            Log.e("Mock Http Response", e.toString());
        }
    }

    @Override
    public Selector getSelector() {
        return null;
    }

    @Override
    public String brewStatement(boolean paramBoolean) {
        String str = "httpResponseQueue.add(";
        //Log.d("brewStatement", params.toString());
        str += "\"" + params.toString().replaceAll("\"", "\"") + "\"";
        str += ")";
        return str;
    }

    @Override
    public void setStatement(String statement) {

    }

    @Override
    public String getTypeString() {
        return "MockedHttpResponse";
    }

    @Override
    public String getValue() {
        return null;
    }
}
